<template>
  <div>
    <basic-container>
      <avue-form :option="option"
                 v-model="form"
                 @tab-click="handleTabClick"
                 @submit="handleSubmit">
        <template slot-scope="{disabled,size}" slot="label">
          <div
            v-if="form.labelJson && form.labelJson !== ''"
            :key="key" v-for="(item, key) in form.labelJson"
          >
            <span>{{ item.name }}：</span>
            <el-tag
              size="small"
              type="success"
            >{{ item.list }}
            </el-tag>
          </div>
        </template>
        <template slot-scope="{disabled,size}" slot="height">
          <span v-if="form.height !== -1">
            <el-tag
              size="small"
              type="success"
            >{{ form.height }} cm</el-tag>
          </span>
          <span v-else>
            <el-tag
              size="small"
              type="danger"
            >未填写</el-tag>
          </span>
        </template>
        <template slot-scope="{disabled,size}" slot="weight">
          <span v-if="form.weight !== -1">
            <el-tag
              size="small"
              type="success"
            >{{ form.weight }} kg</el-tag>
          </span>
          <span v-else>
            <el-tag
              size="small"
              type="danger"
            >未填写</el-tag>
          </span>
        </template>
        <template slot-scope="{disabled,size}" slot="waistline">
          <span v-if="form.waistline !== -1">
            <el-tag
              size="small"
              type="success"
            >{{ form.waistline }} cm</el-tag>
          </span>
          <span v-else>
            <el-tag
              size="small"
              type="danger"
            >未填写</el-tag>
          </span>
        </template>
        <template slot-scope="{disabled,size}" slot="hipline">
          <span v-if="form.hipline !== -1">
            <el-tag
              size="small"
              type="success"
            >{{ form.hipline }} cm</el-tag>
          </span>
          <span v-else>
            <el-tag
              size="small"
              type="danger"
            >未填写</el-tag>
          </span>
        </template>
        <template slot-scope="{disabled,size}" slot="nickname">
          <el-tag v-if="form.nickname" type="success">{{ form.nickname }}</el-tag>
          <el-tag v-else type="info">暂无</el-tag>
        </template>
        <template slot-scope="{disabled,size}" slot="name">
          <el-tag v-if="form.name" type="success">{{ form.name }}</el-tag>
          <el-tag v-else type="info">暂无</el-tag>
        </template>
        <template slot-scope="{disabled,size}" slot="isVip">
          <el-tag v-if="form.isVip" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
        <template slot-scope="{disabled,size}" slot="vipExpireTime">
          <el-tag v-if="form.isVip" type="success">{{ form.vipExpireTime }}</el-tag>
          <el-tag v-else type="danger">{{ form.vipExpireTime }}</el-tag>
        </template>
        <template slot-scope="{disabled,size}" slot="integral">
          <el-tag>{{ form.integral }}</el-tag>
        </template>
        <template slot-scope="{disabled,size}" slot="packages">
          <el-button type="primary" style="float: right; margin-right: 5%; margin-bottom: 10px" @click="scheduleActive">未来七日立即生效</el-button>
          <el-calendar :range="dateRange">
            <template
              slot="dateCell"
              slot-scope="{date, data}">
              <div class="date-cell" :class="data.isSelected ? 'is-selected' : ''">
                <div class="calendar-day">

                </div>
                <el-row :span="24">
                  <el-col :span=24>
                    <div class="date-item" @click="handleEditItem(data)">
                      <div class="date-item-child">
                        <span>减脂午餐餐数: </span>
                        <el-tag :type="formatSchedule(data).lunchCountJZ === 0 ? 'danger' : 'success'">{{ formatSchedule(data).lunchCountJZ }}</el-tag>
                      </div>
                      <div class="date-item-child">
                        <span>减脂午餐主食类型: </span>
                        <span>{{ (formatSchedule(data).lunchMainCourseTypeJZ && formatSchedule(data).lunchMainCourseTypeJZ !== '') ? formatSchedule(data).lunchMainCourseTypeJZ : '未配置' }}</span>
                      </div>
                      <div class="date-item-child">
                        <span>营养午餐餐数: </span>
                        <el-tag :type="formatSchedule(data).lunchCountYY === 0 ? 'danger' : 'success'">{{ formatSchedule(data).lunchCountYY }}</el-tag>
                      </div>
                      <div class="date-item-child">
                        <span>营养午餐主食类型: </span>
                        <span>{{ (formatSchedule(data).lunchMainCourseTypeYY && formatSchedule(data).lunchMainCourseTypeYY !== '') ? formatSchedule(data).lunchMainCourseTypeYY : '未配置' }}</span>
                      </div>
                      <div class="date-item-child">
                        <span>减脂晚餐餐数: </span>
                        <el-tag :type="formatSchedule(data).dinnerCountJZ === 0 ? 'danger' : 'success'">{{ formatSchedule(data).dinnerCountJZ }}</el-tag>
                      </div>
                      <div class="date-item-child">
                        <span>减脂晚餐主食类型: </span>
                        <span>{{ (formatSchedule(data).dinnerMainCourseTypeJZ && formatSchedule(data).dinnerMainCourseTypeJZ !== '') ? formatSchedule(data).dinnerMainCourseTypeJZ : '未配置' }}</span>
                      </div>
                      <div class="date-item-child">
                        <span>营养晚餐餐数: </span>
                        <el-tag :type="formatSchedule(data).dinnerCountYY === 0 ? 'danger' : 'success'">{{ formatSchedule(data).dinnerCountYY }}</el-tag>
                      </div>
                      <div class="date-item-child">
                        <span>营养晚餐主食类型: </span>
                        <span>{{ (formatSchedule(data).dinnerMainCourseTypeYY && formatSchedule(data).dinnerMainCourseTypeYY !== '') ? formatSchedule(data).dinnerMainCourseTypeYY : '未配置' }}</span>
                      </div>
                      <div class="date-item-child">
                        <span>联系人: </span>
                        <span>{{ (formatSchedule(data).receiver && formatSchedule(data).receiver !== '') ? formatSchedule(data).receiver : '未配置' }}</span>
                      </div>
                      <div class="date-item-child">
                        <span>联系电话: </span>
                        <span>{{ (formatSchedule(data).telephone && formatSchedule(data).telephone !== '') ? formatSchedule(data).telephone : '未配置' }}</span>
                      </div>
                      <div class="date-item-child">
                        <span>备注: </span>
                        <span>{{ (formatSchedule(data).remark && formatSchedule(data).remark !== '') ? formatSchedule(data).remark : '未配置' }}</span>
                      </div>
                      <div class="date-item-child">
                        <span>配送地址: </span>
                        <span>{{ formatSchedule(data).address && formatSchedule(data).address.length !== 0 ? formatSchedule(data).address[2] : '未配置' }}</span>
                        <span>{{ formatSchedule(data).addressDetail && formatSchedule(data).addressDetail !== '' ? (' - ' + formatSchedule(data).addressDetail) : '' }}</span>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </template>
          </el-calendar>
          <el-dialog title="配置"
                     append-to-body
                     :visible.sync="itemVisible"
                     :close-on-click-modal="false"
                     :close-on-press-escape="false"
                     :show-close="false"
                     width="30%">
            <el-form :model="packagesForm" ref="form" label-width="150px" class="food-select-form">
              <el-form-item label="星期: ">
                <el-tag>{{ packagesForm.week }}</el-tag>
              </el-form-item>
              <el-form-item label="地址: ">
                <el-select style="width: 300px;" placeholder="请选择地址" v-model="addressIndex" @change="addressChange" clearable>
                  <el-option :key="index" v-for="(address, index) in addressList" :value="index" :label="address.details">
                    <span v-if="address.public">{{ address.details }}【拼团地址】</span>
                    <span v-else>{{ address.details }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="联系人: ">
                <el-input style="width: 300px;" placeholder="请输入联系人" v-model="packagesForm.receiver" ></el-input>
              </el-form-item>
              <el-form-item label="联系电话: ">
                <el-input style="width: 300px;" type="number" placeholder="请输入联系电话" v-model="packagesForm.telephone" ></el-input>
              </el-form-item>
              <el-form-item label="备注: ">
                <el-input style="width: 300px;" type="textarea" placeholder="请输入备注" v-model="packagesForm.remark" ></el-input>
              </el-form-item>
              <el-form-item label="减脂午餐份数: ">
                <el-input style="width: 300px;" type="number" v-model="packagesForm.lunchCountJZ" ></el-input>
              </el-form-item>
              <el-form-item label="减脂午餐主食类型: ">
                <el-select style="width: 300px;" placeholder="请选择主食类型" v-model="packagesForm.lunchMainCourseTypeJZ" >
                  <el-option :key="index" v-for="(mainCourseType, index) in mainCourseTypes" :value="mainCourseType.value" :label="mainCourseType.label">
                    {{ mainCourseType.label }}
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="营养午餐份数: ">
                <el-input style="width: 300px;" type="number" v-model="packagesForm.lunchCountYY" ></el-input>
              </el-form-item>
              <el-form-item label="营养午餐主食类型: ">
                <el-select style="width: 300px;" placeholder="请选择主食类型" v-model="packagesForm.lunchMainCourseTypeYY" >
                  <el-option :key="index" v-for="(mainCourseType, index) in mainCourseTypes" :value="mainCourseType.value" :label="mainCourseType.label">
                    {{ mainCourseType.label }}
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="减脂晚餐份数: ">
                <el-input style="width: 300px;" type="number" v-model="packagesForm.dinnerCountJZ" ></el-input>
              </el-form-item>
              <el-form-item label="减脂晚餐主食类型: ">
                <el-select style="width: 300px;" placeholder="请选择主食类型" v-model="packagesForm.dinnerMainCourseTypeJZ" >
                  <el-option :key="index" v-for="(mainCourseType, index) in mainCourseTypeDinner" :value="mainCourseType.value" :label="mainCourseType.label">
                    {{ mainCourseType.label }}
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="营养晚餐份数: ">
                <el-input style="width: 300px;" type="number" v-model="packagesForm.dinnerCountYY" ></el-input>
              </el-form-item>
              <el-form-item label="营养晚餐主食类型: ">
                <el-select style="width: 300px;" placeholder="请选择主食类型" v-model="packagesForm.dinnerMainCourseTypeYY" >
                  <el-option :key="index" v-for="(mainCourseType, index) in mainCourseTypeDinner" :value="mainCourseType.value" :label="mainCourseType.label">
                    {{ mainCourseType.label }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="handlePackagesClose">取 消</el-button>
        <el-button type="primary" @click="handlePackagesConfirm">确 定</el-button>
      </span>
          </el-dialog>
        </template>
        <template slot-scope="{disabled,size}" slot="packagesOrder">
          <avue-crud :option="packagesOrderOption"
                     :table-loading="loading"
                     :data="data"
                     :page="page"
                     ref="crud"
                     @search-change="searchChange"
                     @search-reset="searchReset"
                     @selection-change="selectionChange"
                     @current-change="currentChange"
                     @size-change="sizeChange"
                     @on-load="onLoad">
            <template slot-scope="{row}" slot="status">
              <el-tag v-if="row.status === 1" type="success">已支付</el-tag>
              <el-tag v-else-if="row.status === 0" type="danger">未支付</el-tag>
              <el-tag v-else-if="row.status === 2" type="danger">关闭</el-tag>
              <el-tooltip v-else-if="row.status === 3"
                          effect="dark"
                          :content="`退款时间: ${row.refundTime}  备注: ${row.refundRemark}`"
                          placement="top">
                <el-tag type="danger">已退款</el-tag>
              </el-tooltip>
              <el-tooltip v-else-if="row.status === 4"
                          effect="dark"
                          :content="`转换时间: ${row.refundTime}  备注: ${row.refundRemark}`"
                          placement="top">
                <el-tag type="danger">已转换</el-tag>
              </el-tooltip>
            </template>
            <template slot-scope="{row}" slot="payType">
              <el-tag v-if="row.payType === 1" type="success">微信</el-tag>
              <el-tag v-else-if="row.payType === 2" type="danger">线下收款</el-tag>
              <el-tag v-else type="danger">未知</el-tag>
            </template>
            <template slot-scope="{row}" slot="isSingle">
              <el-tag v-if="row.isSingle === 1" type="primary">单餐</el-tag>
              <el-tag v-else-if="row.isSingle === 2" type="success">多餐</el-tag>
              <el-tag v-else type="danger">未知</el-tag>
            </template>
            <template slot-scope="{row}" slot="packageId">
              <span>{{ JSON.parse(row.packageJson).name }}</span>
            </template>
            <template slot="menuLeft">
              <div v-if="Object.keys(form.activePackages).length === 0">
                <el-tag type="primary" style="margin-right: 10px">无有效餐卡</el-tag>
                <el-tag :type="form.effectivePackagesCount <= 5 ? 'danger' : 'success'" style="margin-right: 10px">剩余餐时: {{ form.effectivePackagesCount }}</el-tag>
                <el-button type="success"
                           size="small"
                           icon="el-icon-goods"
                           @click="handleManualOrder">人工下单
                </el-button>
              </div>
              <div v-else>
                <el-tag type="primary" style="margin-right: 10px">餐卡：{{ form.activePackages.name }}</el-tag>
                <el-tag :type="form.effectivePackagesCount <= 5 ? 'danger' : 'success'" style="margin-right: 10px">剩余餐时: {{ form.effectivePackagesCount }}</el-tag>
                <el-button type="success"
                           size="small"
                           icon="el-icon-goods"
                           @click="handleManualRenew">续费
                </el-button>
              </div>
            </template>
            <template slot="menu" slot-scope="{row}">
              <el-button size="small"
                         v-if="[1].includes(row.status)"
                         type="text"
                         @click="handleRefund(row)">退款
              </el-button>
            </template>
          </avue-crud>
          <el-dialog :title="orderType === 1 ? '人工下单' : '续费'"
                     append-to-body
                     :visible.sync="orderVisible"
                     :close-on-click-modal="false"
                     :close-on-press-escape="false"
                     :show-close="false"
                     width="30%">
            <el-form :model="orderForm" ref="form" label-width="80px" class="food-select-form">
              <el-form-item label="套餐: ">
                <el-select style="width: 70%;" v-model="orderForm.packagesId" placeholder="请选择套餐" @change="handlePackagesChange">
                  <el-option
                    v-for="item in packagesList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
                <div v-if="Object.keys(packagesSelected).length !== 0">
                  <div>
                    描述：{{ packagesSelected.description }}
                  </div>
                  <div>
                    每餐单价：￥{{ packagesSelected.price }}
                  </div>
                  <div>
                    是否单餐：{{ packagesSelected.isSingle === 1 ? '单餐' : '多餐' }}
                  </div>
                  <div>
                    餐时数：{{ packagesSelected.effectiveCount }}
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="份数: ">
                <el-input style="width: 70%;" type="number" v-model="orderForm.count" @change="handlePackagesChange(orderForm.packagesId)"></el-input>
              </el-form-item>
              <el-form-item label="金额: ">
                <el-tag type="danger">￥{{ orderAmount }}</el-tag>
              </el-form-item>
              <el-form-item label="备注: ">
                <el-input style="width: 70%;" type="textarea" v-model="orderForm.remark"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="handleOrderCancel">取 消</el-button>
        <el-button type="primary" @click="handleOrderConfirm">确 定</el-button>
      </span>
          </el-dialog>
        </template>
        <template slot-scope="{disabled,size}" slot="cookbook">
          <member-cookbook v-if="form.id" :form="form" :addressList="addressList" @reload="handleWitch(true)"></member-cookbook>
        </template>
        <template slot-scope="{disabled,size}" slot="amount">
          <member-payment v-if="form.id" :form="form" @reload="handleWitch(true)"></member-payment>
        </template>
        <template slot-scope="{disabled,size}" slot="address">
          <member-address v-if="form.id" :member="form" @reload="handleWitch(true)"></member-address>
        </template>
      </avue-form>
    </basic-container>
  </div>
</template>

<script>
import option from "@/const/member/info";
import mainCourseTypes from "@/const/common/mainCourseType";
import mainCourseTypeDinner from "@/const/common/mainCourseTypeDinner";
import {getDetail, update, savePackagesCycle, scheduleActive} from "@/api/member/member";
import {getList as getAddressList} from "@/api/member/member_address";
import {getList as getPackageOrderList, manualOrder, refund, getChangeAmount} from "@/api/packages/packages_order";
import {getSelect as getPackagesList} from "@/api/packages/packages";
import { memberGroup } from "@/api/delivery/member_delivery_bind";
import func from "@/util/func";
import { dateFormat } from "@/util/date";
import {updatePassword} from "../../api/system/user";
import {deepClone} from '../../util/util'
import MemberCookbook from "./components/member_cookbook";
import MemberPayment from "./components/member_payment";
import MemberAddress from "./components/member_address";


export default {
  name: "MemberDetail",
  props: {
    id: {
      type: String,
      default: ''
    },
    tab: {
      type: String,
      default: ''
    },
  },
  components: {MemberCookbook, MemberPayment, MemberAddress},
  data() {
    return {
      mainCourseTypes: mainCourseTypes,
      mainCourseTypeDinner: mainCourseTypeDinner,
      index: 0,
      option: option,
      form: {},
      dateRange: [],
      query: {},
      loading: true,
      page: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      packagesOrderOption: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 100,
        selection: false,
        refreshBtn: false,
        column: [
          {
            label: "套餐",
            prop: "packageId",
            slot: true,
            rules: [{
              required: true,
              message: "请选择套餐",
              trigger: "blur"
            }],
            type: "select",
            dicUrl: '/api/celery-packages/packages/select',
            props: {
              label: "name",
              value: "id"
            },
          },
          {
            label: "金额",
            prop: "amount",
            rules: [{
              required: true,
              message: "请输入金额",
              trigger: "blur"
            }]
          },
          {
            label: "支付金额",
            prop: "payAmount",
          },
          {
            label: "支付方式",
            prop: "payType",
            slot: true,
          },
          {
            label: "是否单餐",
            prop: "isSingle",
            slot: true,
          },
          {
            label: "剩余有效餐时",
            prop: "effectiveCount",
          },
          {
            label: "套餐总餐时",
            prop: "totalCount",
          },
          {
            label: "时间",
            prop: "createTime",
            rules: [{
              required: true,
              message: "请输入创建时间",
              trigger: "blur"
            }]
          },
          {
            label: "状态",
            prop: "status",
            slot: true,
            rules: [{
              required: true,
              message: "请输入状态（0 = 创建, 1 = 成功, 2 = 取消）",
              trigger: "blur"
            }]
          },
          {
            label: "过期日期",
            prop: "expireDate",
          },
        ]
      },
      data: [],
      packagesForm: {
        address: [],
        addressDetail: '',
        lunchCountJZ: 0,
        lunchCountYY: 0,
        dinnerCountJZ: 0,
        dinnerCountYY: 0,
        telephone: '',
        mainCourseType: '',
        remark: '',
      },
      itemVisible: false,
      orderVisible: false,
      addressList: [],
      addressIndex: '',
      orderType: '',
      orderForm: {
        count: 1
      },
      orderAmount: 0,
      packagesList: [],
      packagesSelected: {},
    };
  },
  computed: {
    formatSchedule() {
      return (data)=> {
        const week = new Date(data.day).getDay()
        let item = this.packagesCycle[`week_${week}`]
        if (!item) {
          item = {
            week: this.formatWeekText(data),
            weekIndex: week,
            address: [],
            addressDetail: '',
            telephone: '',
            lunchCountJZ: 0,
            lunchCountYY: 0,
            dinnerCountJZ: 0,
            dinnerCountYY: 0,
          }
        }
        return item
      }
    },
    packagesCycle() {
      try {
        return JSON.parse(this.form.packagesCycle)
      } catch (e) {
        return {}
      }
    },
    formatWeekText() {
      return (data)=> {
        const week = new Date(data.day).getDay()
        switch (week) {
          case 1:
            return '周一'
          case 2:
            return '周二'
          case 3:
            return '周三'
          case 4:
            return '周四'
          case 5:
            return '周五'
          case 6:
            return '周六'
          case 0:
            return '周日'
          default:
            return week
        }
      }
    }
  },
  created() {
    if (this.tab && this.tab !== '') {
      this.option.tabsActive = parseInt(this.tab)
    }
    if (this.$route.query.tab) {
      this.option.tabsActive = parseInt(this.$route.query.tab)
    }
    this.handleWitch();
    this.getCurrentWeek();
  },
  methods: {
    scheduleActive() {
      this.$confirm("确定立即生效该客户未来七日计划?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return scheduleActive(this.form.id);
        })
        .then(() => {
          this.onLoad(this.page)
          this.handleWitch(true)
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    addressChange(index) {
      this.packagesForm.receiver = this.addressList[index].name
      this.packagesForm.telephone = this.addressList[index].tel
    },
    handleRefund(row) {
      this.$confirm("套餐内有效餐时将清零，不可撤回，退款后该套餐关联已有的选餐不可取消，确定退款该套餐订单?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return refund(row.id, "人工退款");
        })
        .then(() => {
          this.onLoad(this.page)
          this.handleWitch(true)
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleOrderCancel() {
      this.orderForm = {
        count: 1
      }
      this.orderAmount = 0
      this.orderVisible = false
      this.packagesList = []
      this.packagesSelected = {}
      this.handleWitch(true)
      this.onLoad(this.page)
    },
    handleOrderConfirm() {
      const params = this.orderForm
      params.memberId = this.form.id
      manualOrder(params).then(res => {
        if (res.data.success) {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.handleWitch(true)
          this.handleOrderCancel()
        } else {
          this.$message({
            type: "error",
            message: res.data.msg
          });
        }
      })
    },
    handlePackagesChange(val) {
      console.log(val)
      this.packagesList.forEach(item => {
        if (item.id === val) {
          this.packagesSelected = item
        }
      })
      const count = this.orderForm.count ? this.orderForm.count : 1
      this.orderAmount = 0
      getChangeAmount(val, this.form.id, count).then(res => {
        this.orderAmount = res.data.data
      })
    },
    handleManualOrder() {
      this.orderVisible = true
      this.orderType = 1
      this.loadPackages()
    },
    handleManualRenew() {
      this.orderVisible = true
      this.orderType = 2
      this.loadPackages()
    },
    loadPackages() {
      getPackagesList().then((res) => {
        this.packagesList = res.data.data
        if (this.orderType === 2) {
          this.orderForm.packagesId = this.form.activePackagesId
          this.handlePackagesChange(this.form.activePackagesId)
        }
      })
    },
    handleEditItem(data) {
      this.itemVisible = true
      const week = new Date(data.day).getDay()
      const tmpPackagesCycle = deepClone(this.packagesCycle)
      let packagesCycleItem = tmpPackagesCycle[`week_${week}`]
      this.addressList = []
      getAddressList(1, 1000, {memberId: this.form.id}).then(res => {
        this.addressList = res.data.data.records

        if (!packagesCycleItem) {
          packagesCycleItem = {
            address: '',
            addressDetail: '',
            telephone: '',
            lunchCountJZ: 0,
            lunchCountYY: 0,
            dinnerCountJZ: 0,
            dinnerCountYY: 0,
          }
        }
        packagesCycleItem.week = this.formatWeekText(data)
        packagesCycleItem.weekIndex = week
        if (packagesCycleItem.address) {
          this.addressList.forEach((address, index) => {
            if (packagesCycleItem.addressDetail === address.details) {
              this.addressIndex = index
            }
          })
        }
        this.packagesForm = packagesCycleItem

        memberGroup(this.form.id).then(res => {
          if (res.data.data.code) {
            const data = res.data.data
            const addressSplitArr = data.address.split('-')
            this.addressList.unshift({
              address: addressSplitArr[0],
              details: addressSplitArr[1],
              name: data.receiverName,
              tel: data.telephone,
              public: true
            })
            if (packagesCycleItem.address) {
              this.addressList.forEach((address, index) => {
                if (packagesCycleItem.addressDetail === address.details) {
                  this.addressIndex = index
                }
              })
            }
            this.packagesForm = packagesCycleItem
          }
        })
      })
    },
    handlePackagesClose() {
      this.packagesForm = {
        address: []
      }
      this.itemVisible = false
    },
    handlePackagesConfirm() {
      const tmpPackagesCycle = deepClone(this.packagesCycle)
      this.packagesForm.addressDetail = this.addressList[this.addressIndex].details
      this.packagesForm.address = ['1', '1', this.addressList[this.addressIndex].address]
      delete this.packagesForm.addressId
      tmpPackagesCycle[`week_${this.packagesForm.weekIndex}`] = this.packagesForm
      this.form.packagesCycle = JSON.stringify(tmpPackagesCycle)
      savePackagesCycle(this.form.id, this.form.packagesCycle).then(res => {
        if (res.data.success) {
          this.$message({
            type: "success",
            message: "修改信息成功!"
          });
          this.handlePackagesClose()
        } else {
          this.$message({
            type: "error",
            message: res.data.msg
          });
        }
      }, error => {
        window.console.log(error);
      })
    },
    handleEditItemBak(data, meal) {
      const week = new Date(data.day).getDay()
      const hasPackage = this.formatSchedule(data, meal)
      this.$confirm(`确定将${hasPackage ? '【配送】' : '【停止】'}改为${hasPackage ? '【停止】' : '【配送】'} ？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const tmpPackagesCycle = deepClone(this.packagesCycle)
        let packagesCycleItem = tmpPackagesCycle[`week_${week}`]
        if (packagesCycleItem) {
          packagesCycleItem[`${meal}_send`] = !hasPackage
        } else {
          packagesCycleItem = {
            lunch_send: false,
            dinner_send: false,
            address: '',
          }
          packagesCycleItem[`${meal}_send`] = !hasPackage
        }
        tmpPackagesCycle[`week_${week}`] = packagesCycleItem
        this.form.packagesCycle = JSON.stringify(tmpPackagesCycle)
        savePackagesCycle(this.form.id, this.form.packagesCycle).then(res => {
          if (res.data.success) {
            this.$message({
              type: "success",
              message: "修改信息成功!"
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.msg
            });
          }
        }, error => {
          window.console.log(error);
        })
      })
    },
    getCurrentWeek() {
      const now = new Date();
      const nowTime = now.getTime();
      const day = now.getDay();
      const oneDayTime = 24 * 60 * 60 * 1000;
      const mondayTime = nowTime - (day - 1) * oneDayTime;
      const sundayTime = nowTime + (7 - day) * oneDayTime;
      const monday = new Date(mondayTime);
      const sunday = new Date(sundayTime);
      this.dateRange = [dateFormat(monday), dateFormat(sunday)]
    },
    handleSubmit(form, done) {
      if (this.index === 0) {
        update(form).then(res => {
          if (res.data.success) {
            this.$message({
              type: "success",
              message: "修改信息成功!"
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.msg
            });
          }
          done();
        }, error => {
          window.console.log(error);
          done();
        })
      } else {
        updatePassword(form.oldPassword, form.newPassword, form.newPassword1).then(res => {
          if (res.data.success) {
            this.$message({
              type: "success",
              message: "修改密码成功!"
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.msg
            });
          }
          done();
        }, error => {
          window.console.log(error);
          done();
        })
      }
    },
    handleWitch(force = false) {
      if (this.index === 0 || force === true) {
        const id = this.id
        getDetail(id).then(res => {
          this.form = res.data.data
          try {
            this.form.labelJson = JSON.parse(this.form.label)
          } catch (e) {
            console.log(e)
          }

          this.addressList = []
          getAddressList(1, 1000, {memberId: this.form.id}).then(res => {
            this.addressList = res.data.data.records

            memberGroup(this.form.id).then(res => {
              if (res.data.data.code) {
                const data = res.data.data
                const addressSplitArr = data.address.split('-')
                this.addressList.unshift({
                  address: addressSplitArr[0],
                  details: addressSplitArr[1],
                  name: data.receiverName,
                  tel: data.telephone,
                  public: true
                })
              }
            })
          })
        });
      }
    },
    handleTabClick(tabs) {
      this.index = func.toInt(tabs.index);
      this.handleWitch();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage){
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize){
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.query.orderType = 1
      params.memberId = this.id
      // params.status = 1
      getPackageOrderList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.date-item {
  height: 100%;
  opacity: 0.8;
  vertical-align: middle;
}

.date-item-child {
  margin-bottom: 5px;
}

.lunch {
  background-color: #f0f175;
}

.dinner {
  background-color: #7ff176;
}

.meal-check {
  margin-left: 10px;
}

.el-calendar__title {
  display: none;
}

.el-select-dropdown .el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  padding: 0 20px !important;
}
</style>
